import com.nepu.gmall.realtime.bean.UnknowBean;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @author chenshuaijun
 * @create 2023-02-24 20:52
 */
public class Flink_LookUpJoin {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        TableResult tableResult = tableEnv.executeSql("CREATE TEMPORARY TABLE base_dic ( " +
                "  dic_code String, " +
                "  dic_name STRING, " +
                "  parent_code STRING " +
                ") WITH ( " +
                "  'connector' = 'jdbc', " +
                "  'url' = 'jdbc:mysql://hadoop102:3306/gmall', " +
                "  'table-name' = 'base_dic', " +
                "  'username' = 'root', " +
                "  'driver' = 'com.mysql.cj.jdbc.Driver'," +
                "  'password' = '12345678' " +
                ")");

//        tableEnv.sqlQuery("select * from base_dic").execute().print();

        SingleOutputStreamOperator<UnknowBean> stream = env.socketTextStream("hadoop102", 9999).map(new MapFunction<String, UnknowBean>() {
            @Override
            public UnknowBean map(String value) throws Exception {
                String[] fields = value.split(",");
                return new UnknowBean(fields[0], fields[1], fields[2]);
            }
        }).assignTimestampsAndWatermarks(WatermarkStrategy.<UnknowBean>forBoundedOutOfOrderness(Duration.ZERO).withTimestampAssigner(new SerializableTimestampAssigner<UnknowBean>() {
            @Override
            public long extractTimestamp(UnknowBean element, long recordTimestamp) {
                return Long.parseLong(element.getScore());
            }
        }));

        Table table = tableEnv.fromDataStream(stream, $("id"), $("uv"), $("score"), $("pt").proctime());

        tableEnv.createTemporaryView("t1",table);

        tableEnv.sqlQuery("select  " +
                "   dic.dic_code,  " +
                "   dic.dic_name,  " +
                "   t1.uv  " +
                "from base_dic dic join t1 on dic.dic_code = t1.id").execute().print();

    }
}
